﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Input;

namespace engine
{
    public class Engine
    {
        // returns singleton instance of Engine
        public static Engine Instance { get { return instance; } }

        // properties
        public Game Game { get { return game; } }
        public ContentManager Content { get { return content; } }
        public ScreenManager ScreenMgr { get { return screenMgr; } }
        public GraphicsDeviceManager GraphicsManager { get { return graphicsManager; } }
        public GraphicsDevice Graphics { get { return graphics; } }

        // private fields
        private static Engine instance = null;
        private Game game = null;
        private ContentManager content = null;
        private ScreenManager screenMgr = null;
        private SpriteBatch spriteBatch = null;

        private GraphicsDeviceManager graphicsManager = null;
        private GraphicsDevice graphics = null;

        public Engine(Game theGame)
        {
            game = theGame;
            graphicsManager = new GraphicsDeviceManager(game);
            instance = this;
        }

        public void Initialize()
        {
            graphics = game.GraphicsDevice;

            Settings.ReadVars();

            graphicsManager.PreferredBackBufferWidth = (int)Settings.Var["WINDOW_WIDTH"];
            graphicsManager.PreferredBackBufferHeight = (int)Settings.Var["WINDOW_HEIGHT"];
            graphicsManager.IsFullScreen = false;
            graphicsManager.SynchronizeWithVerticalRetrace = false;
            graphicsManager.ApplyChanges();
            game.IsFixedTimeStep = false;

            spriteBatch = new SpriteBatch(game.GraphicsDevice);

            Mouse.SetPosition(Game.GraphicsDevice.Viewport.Width / 2, Game.GraphicsDevice.Viewport.Height / 2);

            Text2D.Initialize(spriteBatch);  // Initialize Text Rendering with a spriteBatch to render to.         
            
        }

        public void LoadContent()
        {
            content = new ContentManager(game.Services, "Content");
            screenMgr = new ScreenManager();

            Text2D.LoadContent();
        }

        public void Update(GameTime gameTime)
        {
            Input.Update();

            screenMgr.Update();
            screenMgr.UpdateScreen(gameTime);
        }

        public void Draw(GameTime gameTime)
        {
            graphics.Clear(Color.CornflowerBlue);

            screenMgr.DrawScreen(gameTime);

            Text2D.Draw(FpsMeter.CountFPS(gameTime).ToString(), new Vector2(0, 0), Color.Red, new Vector2(2, 2));   // Function responsible for counting and rendering the framerate.
        }
    }
}
